package com.turbo.cloud.gateway.filter;

import com.turbo.cloud.gateway.filter.auth.ApiAuthLogic;
import com.turbo.cloud.gateway.filter.auth.InterfaceAuthLogic;
import com.turbo.cloud.gateway.utils.AuthUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 网关授权的核心过滤器
 * order的规则： order的值越小，优先级越高 order如果不标注数字，默认最低优先级，因为其默认值是int最大值
 *
 * @author zhangluning
 */
@Order(-100)
@Slf4j
@RequiredArgsConstructor
@Component
public class GatewayAuthFilter implements WebFilter {

    final ApiAuthLogic apiAuthLogic;
    final InterfaceAuthLogic interfaceAuthLogic;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return this.doAuth(exchange, chain);
    }

    private Mono<Void> doAuth(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (apiAuthLogic.validatePermission(request)) {
            // Interface授权验证
            if (interfaceAuthLogic.validateSecretKey(request)) {
                return chain.filter(exchange);
            } else {
                return AuthUtil.unSuccessAuth(response, "访问被拒绝：请提供的认证信息验证不通过");
            }
        } else {
            return AuthUtil.unSuccessAuth(response, "访问被拒绝：用户访问权限受限");
        }
    }
}
